import React, { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import {
  Select,
  Button,
  Table,
  Input,
  message,
  TreeSelect,
  Modal,
  Progress,
} from "antd";
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  SearchOutlined,
  ApiOutlined,
} from "@ant-design/icons";
import {
  text_check,
  post_axios,
  format_time,
  get_interval_date,
} from "../../utils";

export default function GoodsStock(props) {
  const { t } = useTranslation();
  const { Option } = Select;
  const [tableHeight, setTableHeight] = useState(0);
  const { actions, setSpinning } = props;
  let { menu_action, user_power_lang, username, user_grade } = actions;
  user_power_lang = JSON.parse(user_power_lang);

  // 国内国外判断
  const session_company = sessionStorage.getItem("company");
  let localStorage_company = JSON.parse(localStorage.getItem("choose_company"));
  const local_company_object =
    localStorage_company &&
    localStorage_company[username] &&
    localStorage_company[username]
      ? localStorage_company[username]
      : "";

  const [page, setPage] = useState(1);
  const [rows, setRows] = useState(20);
  const [total, setTotal] = useState(0);
  const [com_ids_par, setCom_ids_par] = useState([]);
  const [mch_ids_par, setMch_ids_par] = useState([]);
  const [project_ids_par, setProject_ids_par] = useState([]);
  const [point_ids_par, setPoint_ids_par] = useState([]);
  const [avm_s, setAvm_s] = useState("");
  const [avm_location_status_list, setAvm_location_status_list] = useState([]);

  const getData = async (newPage, newRows, sort_key, sort_type) => {
    let upMsg = {
      page: newPage ? newPage : page,
      rows: newRows ? newRows : rows,
      company_id: local_company_object.id,
      company: local_company_object.company,
      com_ids_par: com_ids_par,
      mch_ids_par: mch_ids_par,
      project_ids_par: project_ids_par,
      point_ids_par: point_ids_par,
      avm_s: avm_s,
      sort_key,
      sort_type,
    };
    setSpinning(true);
    let res = await post_axios("goods_stock", "m_query", upMsg);
    setSpinning(false);
    if (!res) return;
    setAvm_location_status_list(res.data_rows.rows);
    setTotal(res.data_rows.total);
  };
  const columns = [
    {
      dataIndex: "idx",
      align: "center",
      width: 40,
      render: (_, record, index) => <>{index + 1}</>,
    },
    {
      title: t("operate.avm"),
      dataIndex: "avm",
      align: "center",
    },
    {
      title: t("operate.avmID"),
      dataIndex: "avmID",
      align: "center",
    },
    {
      title: `${t("operate.project")} | ${t("operate.point")}`,
      align: "center",
      render: (_, record) => (
        <div>
          <div>{record.project}</div>
          <div>{record.point}</div>
        </div>
      ),
    },
    {
      title: t("operate.goods_nu"),
      dataIndex: "goods_nu",
      align: "center",
    },
    {
      title: t("operate.goods_shortage_rate"),
      align: "center",
      render: (_, record) => (
        <div
          style={{
            display: "flex",
            alignItems: "center",
            justifyContent: "flex-start",
            width: "100%",
          }}
        >
          <div style={{ width: "65%" }}>
            <Progress
              showInfo={false}
              status="active"
              percent={Number((record.goods_shortage_rate * 100).toFixed(2))}
            />
          </div>
          <div>{Number((record.goods_shortage_rate * 100).toFixed(2))}%</div>
        </div>
      ),
      key: "goods_shortage_rate",
      sorter: true,
    },
    {
      title: t("operate.goods_empty_rate"),
      align: "center",
      render: (_, record) => (
        <div
          style={{
            display: "flex",
            alignItems: "center",
            justifyContent: "flex-start",
            width: "100%",
          }}
        >
          <div style={{ width: "65%" }}>
            <Progress
              showInfo={false}
              status="active"
              percent={Number((record.goods_empty_rate * 100).toFixed(2))}
            />
          </div>
          <div>{Number((record.goods_empty_rate * 100).toFixed(2))}%</div>
        </div>
      ),
      key: "goods_empty_rate",
      sorter: true,
    },
    {
      title: t("operate.slot_nu"),
      align: "center",
      dataIndex: "slot_nu",
    },
    {
      title: t("operate.slot_shortage_rate"),
      align: "center",
      render: (_, record) => (
        <div
          style={{
            display: "flex",
            alignItems: "center",
            justifyContent: "flex-start",
            width: "100%",
          }}
        >
          <div style={{ width: "65%" }}>
            <Progress
              showInfo={false}
              status="active"
              percent={Number((record.slot_shortage_rate * 100).toFixed(2))}
            />
          </div>
          <div>{Number((record.slot_shortage_rate * 100).toFixed(2))}%</div>
        </div>
      ),
      key: "slot_shortage_rate",
      sorter: true,
    },
    {
      title: t("operate.slot_empty_rate"),
      align: "center",
      render: (_, record) => (
        <div
          style={{
            display: "flex",
            alignItems: "center",
            justifyContent: "flex-start",
            width: "100%",
          }}
        >
          <div style={{ width: "65%" }}>
            <Progress
              showInfo={false}
              status="active"
              percent={Number((record.slot_empty_rate * 100).toFixed(2))}
            />
          </div>
          <div>{Number((record.slot_empty_rate * 100).toFixed(2))}%</div>
        </div>
      ),
      key: "slot_empty_rate",
      sorter: true,
    },
    {
      title: t("operate.avm_stock"),
      align: "center",
      dataIndex: "avm_stock",
    },
    {
      title: t("operate.avm_container"),
      align: "center",
      dataIndex: "avm_container",
    },
    {
      title: t("operate.update_time"),
      align: "center",
      render: (_, record) => <>{format_time(record.op_time, "type_s")}</>,
    },
  ];

  const tableOnChange = (pagination, filters, sorter, extra) => {
    const { action } = extra;
    if (action !== "sort") return;
    const { order, columnKey } = sorter;
    if (!order) {
      getData();
      return;
    }
    if (order === "ascend") {
      getData(page, rows, `mega_avm_stock_rate.${columnKey}`, "asc");
    } else {
      getData(page, rows, `mega_avm_stock_rate.${columnKey}`, "desc");
    }
  };
  // 分页器
  const pageOnChange = async (page, pageSize) => {
    setPage(page);
    setRows(pageSize);
    initData(page, pageSize);
  };

  // 用户数据行点击
  const [clickRowKey, setClickRowKey] = useState([]);
  const [clickRow, setclickRow] = useState([]);

  const tableRowClick = (row) => {
    const avm = row.avm;
    const idx = clickRowKey.indexOf(avm);
    if (idx > -1) {
      const clickAvm = clickRowKey.filter((item) => item !== avm);
      setClickRowKey(clickAvm);
      //   setClickRow(clickRow.splice(idx, 1));
    } else {
      setClickRowKey([...clickRowKey, avm]);
      //   setClickRow([...clickRow, row]);
    }
  };

  const search_data = () => {
    setPage(1);
    initData(1);
  };

  const initData = (page, rows) => {
    setClickRowKey([]);
    setclickRow([]);
    getData(page, rows);
  };

  const [avm_goods_stock_show, setAvm_goods_stock_show] = useState(false);
  const [avm_goods_stock_data, setAvm_goods_stock_data] = useState([]);
  const export_goods_stock_data = async () => {
    let upMsg = {
      company_id: local_company_object.id,
      company: local_company_object.company,
    };
    if (clickRowKey.length !== 0) {
      //使用选中的机器进行导出
      Object.assign(upMsg, {
        avm_s: clickRowKey.join(","),
      });
    } else {
      // 导出全部筛选后的机器
      Object.assign(upMsg, {
        com_ids_par: com_ids_par,
        mch_ids_par: mch_ids_par,
        project_ids_par: project_ids_par,
        point_ids_par: point_ids_par,
        avm_s: avm_s,
      });
    }
    let res = await post_axios("goods_stock", "m_stat_stock", upMsg);
    if (!res) return;
    setAvm_goods_stock_data(res.data_rows.rows);
    setAvm_goods_stock_show(true);
  };
  const stockColumns = [
    {
      dataIndex: "idx",
      align: "center",
      width: 40,
      render: (_, record, index) => <>{index + 1}</>,
    },
    {
      title: t("operate.goods_name"),
      dataIndex: "name",
      align: "center",
    },
    {
      title: t("operate.goods_barcode"),
      dataIndex: "barcode",
      align: "center",
    },
    {
      title: t("operate.allowance_new"),
      dataIndex: "stock",
      align: "center",
      sorter: (a, b) => a.stock - b.stock,
    },
    {
      title: t("operate.capacity"),
      dataIndex: "container",
      align: "center",
      sorter: (a, b) => a.container - b.container,
    },
    {
      title: t("operate.shortage"),
      align: "center",
      defaultSortOrder: "descend",
      sorter: (a, b) => a.container - a.stock - (b.container - b.stock),
      render: (_, record, index) => <>{record.container - record.stock}</>,
    },
  ];

  // 获取组织列表
  const [com_list, setCom_list] = useState([]);
  const get_com_data = async () => {
    let upMsg = {
      company_id: local_company_object.id,
      company: local_company_object.company,
      op_type: "list_com_id",
    };
    let res = await post_axios("admin_oneself", "m_query", upMsg);
    if (!res) return;
    setCom_list(res.data_rows.rows);
  };

  // 筛选_获取商户列表
  const [mch_page, setMch_page] = useState(1);
  const [mch_list, setMch_list] = useState([]);
  const get_mch_data = async (newPage) => {
    let upMsg = {
      page: newPage ? newPage : mch_page,
      rows: 20,
      company_id: local_company_object.id,
      company: local_company_object.company,
      op_type: "list_mch",
    };
    let res = await post_axios("admin_oneself", "m_query", upMsg);
    if (!res) return;
    const receiveRows = res.data_rows.rows;
    setMch_list([...mch_list, ...receiveRows]);
  };
  // 商户筛选框-分页
  const mch_next_page = () => {
    setMch_page(mch_page + 1);
    get_mch_data(mch_page + 1);
  };

  // 筛选_获取项目列表
  const [project_page, setProject_page] = useState(1);
  const [project_rows, setProject_rows] = useState(20);
  const [project_list, setProject_list] = useState([]);
  const get_project_data = async (newPage) => {
    let upMsg = {
      page: newPage ? newPage : project_page,
      rows: project_rows,
      company_id: local_company_object.id,
      company: local_company_object.company,
      op_type: "list_project",
    };
    let res = await post_axios("admin_oneself", "m_query", upMsg);
    if (!res) return;
    setProject_list(res.data_rows.rows);
  };
  const project_next_page = () => {
    setProject_page(project_page + 1);
    setProject_ids_par([]);
    get_project_data(project_page + 1);
  };
  // 筛选_获取点位列表
  const [point_page, setPoint_page] = useState(1);
  const [point_list, setPoint_list] = useState([]);
  const get_point_data = async (newPage) => {
    let upMsg = {
      page: newPage ? newPage : point_page,
      rows: 20,
      company_id: local_company_object.id,
      company: local_company_object.company,
      op_type: "list_point",
    };
    let res = await post_axios("admin_oneself", "m_query", upMsg);
    if (!res) return;
    setPoint_list(res.data_rows.rows);
  };
  const point_next_page = () => {
    setPoint_page(point_page + 1);
    setPoint_ids_par([]);
    get_point_data(point_page + 1);
  };

  useEffect(() => {
    // 挂载后或者更新后的操作
    getData().then(() => {
      const tabBoxHeight =
        document.getElementsByClassName("goods_stock")[0].scrollHeight;
      const tableHeight = tabBoxHeight - 96 - 70;
      setTableHeight(tableHeight);
    });
    if (user_grade < 70) {
      get_com_data();
    }
    get_mch_data();
    get_project_data();
    get_point_data();
  }, []);
  return (
    <>
      <div className="goods_stock modules">
        <div className="screen_ipt">
          <div className="ipt_box ipt_box_long">
            <div className="ipt_box_title">{t("transaction_flow.avm")}</div>
            <Input
              placeholder=" "
              value={avm_s}
              size="small"
              allowClear={true}
              onChange={(e) => setAvm_s(e.target.value)}
            />
          </div>
          {user_grade < 70 ? (
            <div className="ipt_box ipt_box_long">
              <div className="ipt_box_title">{t("market.organization")}</div>
              <TreeSelect
                value={com_ids_par}
                treeData={com_list}
                allowClear={true}
                size="small"
                multiple
                treeCheckStrictly={true}
                fieldNames={{
                  label: "com",
                  value: "com_id",
                  children: "children",
                }}
                placeholder=" "
                treeCheckable={true}
                onChange={(newValue) => setCom_ids_par(newValue)}
              />
            </div>
          ) : (
            ""
          )}
          <div className="ipt_box ipt_box_long">
            <div className="ipt_box_title">{t("market.mch_name")}</div>
            <Select
              mode="multiple"
              size="small"
              placeholder=" "
              allowClear={true}
              value={mch_ids_par}
              options={mch_list}
              fieldNames={{
                label: "mch",
                value: "mch_id",
              }}
              onChange={(value) => setMch_ids_par(value)}
              onPopupScroll={(event) => {
                if (mch_list.length < mch_page * 20) {
                  console.log("没有更多商户的筛选数据了");
                  return;
                }
                const target = event.target;
                const residueHeight =
                  target.scrollHeight - target.scrollTop - target.clientHeight;
                if (residueHeight <= 50) {
                  mch_next_page();
                }
              }}
              optionFilterProp="mch"
            ></Select>
          </div>

          <div className="ipt_box ipt_box_long">
            <div className="ipt_box_title">{t("market.project")}</div>
            <Select
              mode="multiple"
              size="small"
              placeholder=" "
              allowClear={true}
              value={project_ids_par}
              options={project_list}
              fieldNames={{
                label: "project",
                value: "project_id",
              }}
              onChange={(value) => setProject_ids_par(value)}
              onPopupScroll={(event) => {
                if (project_list.length < project_page * 20) {
                  console.log("没有更多项目的筛选数据了");
                  return;
                }
                const target = event.target;
                const residueHeight =
                  target.scrollHeight - target.scrollTop - target.clientHeight;
                if (residueHeight <= 50) {
                  project_next_page();
                }
              }}
              optionFilterProp="project"
            ></Select>
          </div>
          <div className="ipt_box ipt_box_long">
            <div className="ipt_box_title">{t("market.point")}</div>
            <Select
              mode="multiple"
              size="small"
              placeholder=" "
              allowClear={true}
              value={point_ids_par}
              options={point_list}
              fieldNames={{
                label: "point",
                value: "point_id",
              }}
              onChange={(value) => setPoint_ids_par(value)}
              onPopupScroll={(event) => {
                if (point_list.length < point_page * 20) {
                  console.log("没有更多点位的筛选数据了");
                  return;
                }
                const target = event.target;
                const residueHeight =
                  target.scrollHeight - target.scrollTop - target.clientHeight;
                if (residueHeight <= 50) {
                  point_next_page();
                }
              }}
              optionFilterProp="point"
            ></Select>
          </div>
        </div>
        <div className="screen_btn">
          <div className="btn_box">
            {/* 添加 */}
            {menu_action.indexOf("m_stat_stock") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<PlusOutlined style={{ color: "#1677FF" }} />}
                onClick={export_goods_stock_data}
              >
                {text_check(user_power_lang["m_stat_stock"])}
              </Button>
            ) : (
              ""
            )}

            {/* 查询 */}
            {menu_action.indexOf("m_query") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<SearchOutlined style={{ color: "#1677FF" }} />}
                onClick={search_data}
              >
                {text_check(user_power_lang["m_query"])}
              </Button>
            ) : (
              ""
            )}
          </div>
        </div>
        <div className="table_box">
          <div
            className="page-table"
            style={{
              width: "100vw",
            }}
          >
            <Table
              dataSource={avm_location_status_list}
              size="small"
              bordered
              columns={columns}
              rowKey={(record) => record.avm + record.box_sort_no}
              virtual
              scroll={{
                y: tableHeight,
              }}
              onRow={(record) => {
                return {
                  onClick: () => tableRowClick(record), // 点击行
                };
              }}
              rowClassName={(record, index) => {
                if (clickRowKey.indexOf(record.avm) > -1) {
                  return "row_clicked_style";
                }
              }}
              rowHoverable={false}
              onChange={tableOnChange}
              pagination={{
                defaultCurrent: page,
                defaultPageSize: rows,
                size: "small",
                current: page,
                total: total,
                responsive: true,
                showTotal: (total) =>
                  text_check({
                    msg_cn: `共 ${total} 条`,
                    msg_en: `Total ${total} items`,
                  }),
                onChange: pageOnChange,
              }}
            />
          </div>
        </div>
      </div>

      <Modal
        title={t("operate.shortage_statistics")}
        open={avm_goods_stock_show}
        onCancel={() => setAvm_goods_stock_show(false)}
        classNames={{ body: "edit_dialog_body ", wrapper: "edit_800_style" }}
        maskClosable={false}
        destroyOnClose={true}
        footer={null}
      >
        <Table
          dataSource={avm_goods_stock_data}
          size="small"
          bordered
          columns={stockColumns}
          rowKey="barcode"
          virtual
          scroll={{
            y: 500,
          }}
          pagination={false}
        />
      </Modal>
    </>
  );
}
